package com.eqs.enterprisequestionnaire.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eqs.enterprisequestionnaire.mapper.*;
import com.eqs.enterprisequestionnaire.model.pojo.*;
import com.eqs.enterprisequestionnaire.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class HistoryServiceImpl extends ServiceImpl<ResponseMapper, Response> implements HistoryService {
    @Autowired
    QuestionnaireMapper questionnaireMapper;
    @Autowired
    ResponseMapper responseMapper;
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    AnswerMapper answerMapper;
    @Autowired
    OptionMapper optionMapper;
    @Autowired
    UserService userService;
    @Autowired
    ResponseService responseService;


    @Override
    public List<Integer> getListIdByUserId(Integer userId) {
        QueryWrapper<Response> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("questionnaire_id")
                .eq("user_id", userId)
                .orderByDesc("submitted_time"); // Order by 提交时间 in descending order
        return responseMapper.selectObjs(queryWrapper);
    }
    public List<Response> getListResponseByUserId(Integer userId){
        QueryWrapper<Response> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .orderByDesc("submitted_time"); // Order by 提交时间 in descending order

        List<Response> responseList = responseMapper.selectList(queryWrapper);
        List<Response> responses=new ArrayList<>();
        for(Response r:responseList){
            List<Answer> answerList=getListAnswerByResponseId(r.getId());
            r.setAnswers(answerList);
            responses.add(r);
        }
        return  responses;
    }

    public List<Questionnaire> getListQuestionnaireByUserId(Integer userId){
        List<Response> responseList=getListResponseByUserId(userId);
        List<Questionnaire> result=new ArrayList<>();
        for(Response response:responseList) {
            Integer questionnaireId=response.getQuestionnaireId();
            QueryWrapper<Questionnaire> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id",questionnaireId);
            result.add(questionnaireMapper.selectOne(queryWrapper));
        }
        return result;
    }
    public List<Question> getListQuestionByQuestionnaireId(Integer questionnaireId){
        QueryWrapper<Question> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id",questionnaireId).orderByAsc("ordination");
        return questionMapper.selectList(queryWrapper);
    }

    public List<Option> getListOptionByQuestionId(Integer questionId){
        QueryWrapper<Option> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("question_id",questionId).orderByAsc("ordination");
        return optionMapper.selectList(queryWrapper);
    }
    public List<Answer> getListAnswerByQuestionId(Integer questionId){
        QueryWrapper<Answer> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("question_id",questionId);
        return answerMapper.selectList(queryWrapper);
    }
    public List<Answer> getListAnswerByResponseId(Integer responseId){
        QueryWrapper<Answer> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("response_id",responseId);
        return answerMapper.selectList(queryWrapper);
    }
    public List<Answer> getAnswerOfQuestionPersonally(Integer responseId,Integer questionId){
        QueryWrapper<Answer> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("response_Id",responseId).eq("question_Id",questionId);
        return answerMapper.selectList(queryWrapper);
    }

//    public List<Answer> getListAnswerByResponseId(Integer responseId){
//        QueryWrapper<Answer> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("response_id",responseId);
//        return answerMapper.selectList(queryWrapper);
//    }
    @Override
    public void insertHistoryAssociation(Integer userId,Integer questionnaireId){
        Response association=new Response();
        association.setQuestionnaireId(questionnaireId);
        association.setUserId(userId);
        association.setSubmittedTime(LocalDateTime.now());
    }

    public Question getQuestionByOptionId(Integer optionId){
        Option option = optionMapper.selectById(optionId);
        Integer questionId=option.getQuestionId();
        if (questionId != null) {
            return questionMapper.selectById(questionId);
        } else {
            throw new IllegalArgumentException("Invalid OptionId: No corresponding Question found.");
        }
    }

    @Override
    public Answer getAnswerByOptionId(Integer optionId) {
        // 根据optionId获取Option对象
        Option option = optionMapper.selectById(optionId);

        // 获取Option对象中的questionId
        Integer questionId = option.getQuestionId();

        // 获取该问题下的所有Answer对象
        List<Answer> answers = getListAnswerByQuestionId(questionId);

        // 遍历Answer对象，找到content与optionId相等的Answer
        for (Answer answer : answers) {
            if (optionId.equals(Integer.parseInt(answer.getContent()))) {
                return answer;
            }
        }

            // 如果没有找到匹配的Answer，抛出异常
        throw new IllegalArgumentException("Invalid OptionId: No corresponding Answer found.");
    }

    public Questionnaire getQuestionnaireByQuestionId(Integer questionId){
        QueryWrapper<Questionnaire> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",questionMapper.selectById(questionId).getQuestionnaireId());
        return questionnaireMapper.selectOne(queryWrapper);
    }
    public  List<Response> getListResponseByQuestionnaireId(Integer questionnaireId){
        QueryWrapper<Response> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id",questionnaireId);
        return responseMapper.selectList(queryWrapper);
    }
    public List<Questionnaire> getAllQuestionnaire(){
        List<User> allUsers= userService.getAllUser();
        List<Questionnaire> AllQuestionnaires=new ArrayList<>();
        for(User user:allUsers){
            AllQuestionnaires.addAll(getListQuestionnaireByUserId(user.getId()));
        }
        return AllQuestionnaires;
    }
    public List<Questionnaire> getQuestionnaireByGender(boolean gender){
        List<User> allUsers;
        if(gender)
            allUsers=userService.getAllMaleUsers();
        else
            allUsers=userService.getAllFemaleUsers();
        List<Questionnaire> AllQuestionnaires=new ArrayList<>();
        for(User user:allUsers){
            AllQuestionnaires.addAll(getListQuestionnaireByUserId(user.getId()));
        }
        return AllQuestionnaires;
    }
    public List<Questionnaire> getQuestionnaireByEnterprise(String enterprise){
        List<User> allUsers= userService.getUsersByCompany(enterprise);
        List<Questionnaire> AllQuestionnaires=new ArrayList<>();
        for(User user:allUsers){
            AllQuestionnaires.addAll(getListQuestionnaireByUserId(user.getId()));
        }
        return AllQuestionnaires;
    }
    public List<Questionnaire> getQuestionnaireByAge(Integer minAge,Integer maxAge){
        List<User> allUsers= userService.getUsersByAgeRange(minAge,maxAge);
        List<Questionnaire> AllQuestionnaires=new ArrayList<>();
        for(User user:allUsers){
            AllQuestionnaires.addAll(getListQuestionnaireByUserId(user.getId()));
        }
        return AllQuestionnaires;
    }

    public List<Questionnaire> getQuestionnaireBySelf(Integer authorId){
        QueryWrapper<Questionnaire> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("author_id",authorId);
        return questionnaireMapper.selectList(queryWrapper);
    }
    public Long getCountResponseInQuestionnaire(Integer questionnaireId){
        return responseMapper.selectCount(new QueryWrapper<Response>().eq("questionnaire_id",questionnaireId));
    }
    public Questionnaire getWholeQuestionnaire(Integer questionnaireId){
        Questionnaire questionnaire=questionnaireMapper.selectById(questionnaireId);
        questionnaire.setCount(getCountResponseInQuestionnaire(questionnaireId));
        if(questionnaire==null){
            throw new RuntimeException("查找问卷失败，无问卷");
        }
        List<Question> questions=new ArrayList<>();
        for(Question q:getListQuestionByQuestionnaireId(questionnaireId)){
            q.setOptions(getListOptionByQuestionId(q.getId()));
            questions.add(q);
        }
        questionnaire.setQuestions(questions);
        return questionnaire;
    }

    public Response getResponseByUserAndQuestionnaire(Integer userId,Integer questionnaireId){
        QueryWrapper<Response> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId)
                .eq("questionnaire_id",questionnaireId);
        return responseMapper.selectOne(queryWrapper);
    }
    @Override
    public List<Answer> getAnswerByUserAndQuestion(Integer userId, Integer questionId) {
        Response response = responseService.selectBy2Id(userId,getQuestionnaireByQuestionId(questionId).getId());
        return getAnswerOfQuestionPersonally(response.getId(),questionId);
    }
}
